package org.korecky.gnotedigitalorganizer;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileSystemView;
import org.korecky.gnotedigitalorganizer.panels.LocalLibraryPanel;
import org.korecky.gnotedigitalorganizer.settings.ApplicationSettingsHelper;
import org.korecky.gnotedigitalorganizer.threads.DetectNewDeviceThread;
import org.korecky.gnotedigitalorganizer.threads.DetectNewDeviceThread.NewDeviceDetectedEvent;
import org.korecky.gnotedigitalorganizer.threads.DetectNewDeviceThread.NewDeviceDetectedEventListener;
import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;

/**
 * 
 * @author Vladislav Korecký
 * 
 */
public class MainWindow extends JFrame {
    private static final List<Image> ICONS = Arrays.asList(new ImageIcon(MainWindow.class.getResource("resources/appIcons/icon16.png")).getImage(), new ImageIcon(MainWindow.class.getResource("resources/appIcons/icon32.png")).getImage(), new ImageIcon(MainWindow.class.getResource("resources/appIcons/icon64.png")).getImage(), new ImageIcon(MainWindow.class.getResource("resources/appIcons/icon128.png")).getImage(), new ImageIcon(MainWindow.class.getResource("resources/appIcons/icon256.png")).getImage());
    private AppContext appContext;
    private TrayIcon trayIcon;
    private SystemTray tray;

    private JMenuBar menuBar;
    private JMenu mnFile;
    private JMenuItem mntmExit;
    private JSeparator separator;
    private JMenu mnDevices;
    private JMenuItem mntmAddNewDevice;
    private JMenuItem mntmDeviceManager;
    private LocalLibraryPanel pnlLocalLibrary;

    public MainWindow() {
	super("G-Note Figital Organizer");
	appContext = new AppContext();
	setIconImages(ICONS);
	try {// Use an appropriate Look and Feel
	    UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
	}
	catch (UnsupportedLookAndFeelException ex) {
	    ex.printStackTrace();
	}
	/* Turn off metal's use of bold fonts */
	UIManager.put("swing.boldMetal", Boolean.FALSE);
	// enable anti-aliased text:
	System.setProperty("awt.useSystemAAFontSettings", "on");
	System.setProperty("swing.aatext", "true");

	try {
	    appContext.setAppSettings(ApplicationSettingsHelper.loadApplicationSettings(AppContext.APPLICATION_SETTINGS_PATH));
	}
	catch (Exception e1) {
	    // TODO Auto-generated catch block
	    e1.printStackTrace();
	}
	if (appContext.getAppSettings() == null) {
	    FirstRunWizard firstRunWizard = new FirstRunWizard(this.appContext);
	    firstRunWizard.setVisible(true);
	}

	// Schedule a job for the event-dispatching thread: adding TrayIcon.
	SwingUtilities.invokeLater(new Runnable() {
	    @Override
	    public void run() {
		initComponents();
	    }
	});

	// Check if paired device is connected
	for (File newDevice : File.listRoots()) {
	    // Check if device id pair with G-Note Digital organizer
	    try {
		if (DeviceManager.isDevicePairWihApplication(newDevice.getAbsoluteFile())) {
		    DeviceConnected(newDevice);
		}
	    }
	    catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}

	// Run thread for detecting new device
	DetectNewDeviceThread newDeviceThread = new DetectNewDeviceThread("newDeviceThreadMainApp");
	newDeviceThread.addNewDeviceDetectedEventListener(new NewDeviceDetectedEventListener() {
	    @Override
	    public void newDeviceDetectedEventOccurred(NewDeviceDetectedEvent evt) {
		DetectNewDeviceThread newDeviceThread = (DetectNewDeviceThread) evt.getSource();
		List<File> newDevices = newDeviceThread.getNewDevices();
		FileSystemView fsv = FileSystemView.getFileSystemView();
		for (File newDevice : newDevices) {
		    // Check if device id pair with G-Note Digital organizer
		    try {
			if (DeviceManager.isDevicePairWihApplication(newDevice.getAbsoluteFile())) {
			    DeviceConnected(newDevice);
			}
		    }
		    catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }
		}
	    }
	});
	newDeviceThread.start();
    }

    private void initComponents() {
	setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	addWindowListener(new WindowAdapter() {
	    @Override
	    public void windowClosing(WindowEvent e) {
		try {
		    // setVisible(false);
		    tray.add(trayIcon);
		}
		catch (AWTException e1) {
		    e1.printStackTrace();
		}
	    }
	});
	URL resource = getClass().getResource("resources/appIcons/icon16.png");
	Image image = Toolkit.getDefaultToolkit().getImage(resource);
	setIconImage(image);
	if (SystemTray.isSupported()) {
	    tray = SystemTray.getSystemTray();
	    trayIcon = new TrayIcon(image);
	    trayIcon.setToolTip("Task Logger");
	    trayIcon.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent e) {
		    setVisible(true);
		    // setExtendedState(MainWindow.NORMAL);
		    // repaint();
		    // toFront();
		    // requestFocus();
		    tray.remove(trayIcon);
		}

	    });
	    addWindowListener(new WindowAdapter() {
		@Override
		public void windowIconified(WindowEvent e) {
		    setVisible(false);
		    try {
			tray.add(trayIcon);
		    }
		    catch (AWTException e1) {
			e1.printStackTrace();
		    }
		}

	    });
	}
	setSize(391, 262);

	this.menuBar = new JMenuBar();
	setJMenuBar(this.menuBar);

	this.mnFile = new JMenu("File");
	this.mnFile.setMnemonic(KeyEvent.VK_X);
	this.menuBar.add(this.mnFile);

	this.separator = new JSeparator();
	this.mnFile.add(this.separator);

	this.mntmExit = new JMenuItem("Exit");
	this.mntmExit.setMnemonic(KeyEvent.VK_X);
	this.mntmExit.setAccelerator(KeyStroke.getKeyStroke("control X"));
	this.mntmExit.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		mntmExitActionPerformed(e);
	    }
	});
	this.mnFile.add(this.mntmExit);

	this.mnDevices = new JMenu("Devices");
	this.mnDevices.setMnemonic(KeyEvent.VK_D);
	this.menuBar.add(this.mnDevices);

	this.mntmAddNewDevice = new JMenuItem("Add new device");
	this.mntmAddNewDevice.addActionListener(new ActionListener() {
	    public void actionPerformed(ActionEvent e) {
		mntmAddNewDeviceActionPerformed(e);
	    }
	});
	this.mntmAddNewDevice.setMnemonic(KeyEvent.VK_A);
	this.mnDevices.add(this.mntmAddNewDevice);

	this.mntmDeviceManager = new JMenuItem("Device manager");
	this.mntmDeviceManager.setMnemonic(KeyEvent.VK_M);
	this.mnDevices.add(this.mntmDeviceManager);

	this.pnlLocalLibrary = new LocalLibraryPanel(this.appContext);
	getContentPane().add(this.pnlLocalLibrary, BorderLayout.CENTER);
    }

    private void DeviceConnected(File newDevice) {
	trayIcon.displayMessage("Device connected", "Genius G-Note is connected", TrayIcon.MessageType.INFO);
	ImportWindow importWindow = new ImportWindow(newDevice);
	importWindow.setVisible(true);
    }

    public static void main(String[] args) {
	MainWindow window = new MainWindow();
	window.setVisible(true);
    }

    protected void mntmExitActionPerformed(ActionEvent e) {
	int answer = JOptionPane.showConfirmDialog(this, "Are you sure you want exit \"G-Note Digital Organizer\" application ?", "Exit application", JOptionPane.YES_NO_OPTION);
	if (answer == 0) {
	    this.dispose();
	    System.exit(0);
	}
    }

    protected void mntmAddNewDeviceActionPerformed(ActionEvent e) {
	NewDeviceWindow newDeviceWindow = new NewDeviceWindow();
	newDeviceWindow.setVisible(true);
    }
}